package org.yray.sip.receive;


import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.yray.sip.log.AbstractLog;
import org.yray.sip.packet.BasePacket;
import org.yray.sip.packet.IPacket;

import java.util.HashMap;
import java.util.Map;


@Slf4j
public class BasePacketDispatch extends AbstractLog {

    private static Map<IPacket.MsgType,IHandler> handlerMap=new HashMap<>();

    public void addHandler(IPacket.MsgType msgType, IHandler handler)
    {
        handlerMap.put(msgType,handler);
    }

    public IHandler getHandler(IPacket.MsgType msgType)
    {
        return handlerMap.get(msgType);
    }

    public void dispatch(byte[] bs)
    {
      IPacket.MsgType msgType= BasePacket.msgTypeOf(bs);
      String receivePack=new String(body(bs));
      JSONObject jsonObject= JSONObject.parseObject(receivePack);
      //log(jsonObject.getString("key"),"receive type={},receivePack={}",msgType,receivePack);
      handlerMap.get(msgType).handler(bs);
    }


    byte[] body(byte[] bs)
    {
        byte[] tempBs=new byte[bs.length-16];
        System.arraycopy(bs,16,tempBs,0,bs.length-16);
        return tempBs;
    }
}
